import pandas as pd
import numpy as np

from feature_set.base_feature import RequstData
from data_mapping import raw2_request_params

def prob2score(prob):
    return round(550 - 60 / np.log(2) * np.log(prob / (1 - prob)), 0)

def model_features(lgb_model, importance_type='gain'):
    """
    分析模型特征及权重
    :param lgb_model:
    :param importance_type:
    :return:
    """
    fea_rs = pd.DataFrame(
        {"var": lgb_model.feature_name(), "imp": lgb_model.feature_importance(importance_type=importance_type)}
    ).sort_values("imp", ascending=False)
    # fea_rs = fea_rs[fea_rs['importance'] > 0]
    return fea_rs.sort_values("imp", ascending=False)

# def raw2_request_params(request_json):
#     base_info = request_json['base_info']
#     base_info['tx_id'] = base_info['order_id']
#     base_info['country_abbr'] = 'id'
#     base_info['country_code'] = "62"
#
#     data_sources = request_json['data_sources']
#     applist_data = data_sources['applist_data']
#     sms_data = data_sources['sms_data']
#     contact_list = data_sources['contact_list']
#     calllog_data = data_sources['calllog_data']
#
#     if len(applist_data)>0:
#         user_apps = pd.DataFrame(applist_data)
#     else:
#         user_apps = pd.DataFrame(applist_data,columns=['pkg_name','app_name','first_install_time','last_update_time'])
#     user_apps = user_apps.rename(columns={
#         'pkg_name': 'app_package',
#         'app_name': 'app_name',
#         'first_install_time': 'fi_time',
#         'last_update_time': 'lu_time',
#     })
#     user_apps['isSystem'] = 0
#     user_apps['fi_time'] = pd.to_datetime(user_apps['fi_time'], format='mixed').apply(
#         lambda x: int(x.timestamp() * 1000))
#     user_apps['lu_time'] = pd.to_datetime(user_apps['lu_time'], format='mixed').apply(
#         lambda x: int(x.timestamp() * 1000))
#     user_apps = user_apps[['app_package', 'app_name', 'fi_time', 'lu_time', 'isSystem']].to_dict(orient='records')
#
#     if len(sms_data):
#         user_sms = pd.DataFrame(sms_data)
#     else:
#         user_sms = pd.DataFrame(sms_data,columns=['content','phone','time','type'])
#     user_sms['phone'] = user_sms['phone'].fillna('')
#     user_sms = user_sms.rename(columns={
#         'content': 'body',
#         'phone': 'src_phone',
#         'time': 'time',
#         'type': 'type'
#     })
#     user_sms['phone'] = user_sms['src_phone']
#     user_sms['type'] = user_sms['type'].astype(str)
#     user_sms['read'] = '0'
#     user_sms['time'] = pd.to_datetime(user_sms['time'], format='mixed').apply(
#         lambda x: int(x.timestamp() * 1000)).astype(str)
#     user_sms = user_sms[['body', 'phone', 'read', 'src_phone', 'time', 'type']].to_dict(orient='records')
#
#     if len(calllog_data)>0:
#         user_colllog = pd.DataFrame(calllog_data)
#     else:
#         user_colllog = pd.DataFrame(calllog_data,columns=['contact_number','contact_time','duration','contact_name','contact_comment','type'])
#     user_colllog = user_colllog.rename(columns={
#         'contact_number': 'call_log_number',
#         'duration': 'call_log_duration',
#         'contact_name': 'call_log_address_name',
#         'contact_comment': 'call_log_attribution'
#     })
#     callog_mapping = {
#         '1': 'incoming_call',
#         '2': 'outgoing_call',
#         '3': 'missed_call',
#         '5': 'cancellation_call',
#         '6': 'cancellation_call',
#         '7': 'cancellation_call',
#         '10': 'cancellation_call',
#         '20': 'cancellation_call',
#         '25': 'cancellation_call',
#         '26': 'cancellation_call',
#         '27': 'cancellation_call',
#         '-3': 'cancellation_call',
#         '-5': 'cancellation_call',
#         '-2': 'cancellation_call',
#         '-1': 'cancellation_call',
#         '-10': 'cancellation_call',
#         '-25': 'cancellation_call',
#         '-27': 'cancellation_call',
#     }
#     user_colllog['call_log_address_name'] = user_colllog['call_log_address_name'].fillna('')
#     user_colllog['call_log_attribution'] = user_colllog['call_log_attribution'].fillna('')
#     user_colllog['call_log_connection_status'] = user_colllog['type'].astype(str).map(callog_mapping).fillna(
#         'cancellation_call')
#     user_colllog['calloranswer_time'] = pd.to_datetime(user_colllog['contact_time'], format='mixed').apply(
#         lambda x: int(x.timestamp() * 1000)).astype(str)
#     user_colllog = user_colllog[['call_log_address_name', 'call_log_attribution', 'call_log_connection_status',
#                                  'call_log_duration', 'call_log_number', 'calloranswer_time']].to_dict(orient='records')
#     if len(contact_list)>0:
#         user_contact = pd.DataFrame(contact_list)
#     else:
#         user_contact = pd.DataFrame(contact_list,columns=['user_id','raw_name','phone','relation'])
#     user_contact = user_contact.rename(columns={
#         'user_id': 'appUserId',
#         'raw_name': 'contactName',
#         'phone': 'contactPhoneNumber',
#         'relation': 'contactRelationship'
#     })
#     user_contact = user_contact[['appUserId', 'contactName', 'contactPhoneNumber', 'contactRelationship']].to_dict(
#         orient='records')
#
#     return {
#         'base_info': base_info,
#         'data_sources': {
#             'applist_data': user_apps,
#             'sms_data': user_sms,
#             'contact_list': user_contact,
#             'calllog_data': user_colllog
#         },
#         'applicant':request_json['applicant']
#     }

def tranReq2featurelibData(request_json):
    request_json = raw2_request_params(request_json)
    base_info = request_json.get("base_info", {})
    country_code = base_info.get("country_code", "")
    app_user_id = base_info.get("app_user_id", "")
    tx_id = base_info.get("tx_id", "")
    order_id = base_info.get("order_id", "")
    phone = base_info.get("phone", "")
    nid = base_info.get("nid", "")
    merchant_id = base_info.get("merchant_id", "")
    source = base_info.get("source", 0)
    acq_channel = base_info.get("acq_channel", "")
    device_type = base_info.get("device_type", "")
    apply_time = base_info.get("apply_time", "")
    country_abbr = base_info.get("country_abbr", "")
    data_sources = request_json.get("data_sources", {})
    features = request_json.get("features", {})
    new_old_sign = base_info['new_old_sign']
    models = request_json.get("models", {})
    applicant = request_json.get("applicant", {})
    third_feature = request_json.get("third_feature", {})

    request_data = RequstData()
    request_data.country_code = country_code
    request_data.tx_id = tx_id
    request_data.order_id = order_id
    request_data.phone = phone
    request_data.nid = nid
    request_data.merchant_id = merchant_id
    request_data.source = source
    request_data.acq_channel = acq_channel
    request_data.device_type = device_type
    request_data.apply_time = apply_time
    request_data.data_sources = data_sources
    request_data.models = models
    request_data.country_abbr = country_abbr
    request_data.app_user_id = app_user_id
    request_data.applicant = applicant
    request_data.new_old_sign = new_old_sign
    request_data.third_feature = third_feature
    return order_id, request_data